Barplots with ggplot2

Barplots are a useful way of displaying occurence counts when a histogram isn't quite what you're looking for! In ggplot2, there are two types of bar charts, determined by what is mapped to bar height. By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.

There isn't a really simple,nice way to do this with qplot, so we'll skip straigh to using ggplot.

Let's see how we can create them using the built-in mpg dataset.

ggplot()

In [4]:
library(ggplot2)
In [5]:
# counts (or sums of weights)
g <- ggplot(mpg, aes(class))
# Number of cars in each class:
g + geom_bar()
In [6]:
# Bar charts are automatically stacked when multiple bars are placed
# at the same location
g + geom_bar(aes(fill = drv))
In [7]:
g + geom_bar(aes(fill = drv), position = "fill")
In [8]:
# You can instead dodge, or fill them
g + geom_bar(aes(fill = drv), position = "dodge")

That's it for the basics of barplots!